// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
	console.log("event", event);
	const skip = event.skip
	const action = event.action
	const tempId = event._id
	const isTemp = event.is_template
	const tempIds = event.tempId
	const userInfo = event.userInfo
	const nickName = event.nickName
	let res = '';
	switch (action) {
		case 'getTempitem':
			res = await getTempitem(tempId)
			break;
		case 'getTemplist':
			res = await getTemplist(isTemp, skip, tempIds)
			break;
		case 'getUserList':
			res = await getUserList(userInfo, skip)
			break;
		case 'getNamelist':
			res = await getNamelist(nickName, skip)
			break;
		default:
			res = 'Not Find Action'
			break;
	}
	return {
		msg: '获取成功',
		code: 200,
		data: res
	}
}
// 获取某个昵称的作品
const getNamelist = async (nickName, skip) => {
	console.log('getNamelist', nickName);
	const _openid = await db.collection('user-list').where({
			nickName
		}).field({
			_openid: true
		})
		.get()
		.then(res => res.data[0]._openid)
		.catch(err => err)

	console.log("skip", _openid, skip);
	return await getUserList({
		openId: _openid
	}, skip)
}
// 获取某个人的
const getUserList = async (userInfo, skip) => {
	console.log('getUserList', userInfo);
	return await db.collection('user-works').where({
			_openid: userInfo.openId
		}).limit(10).skip(skip)
		.get()
		.then(res => res.data)
		.catch(err => err)
}
// 获取模板列表
const getTemplist = async (is_template, skip, tempId) => {
	console.log('getTemplist', tempId);
	if (tempId == 0) {
		return await db.collection('user-works').where({
				is_template
			}).limit(10).skip(skip).orderBy('_id','desc')
			.get()
			.then(res => res.data)
			.catch(err => err)
	} else {
		return await db.collection('user-works').where({
				is_template,
				tempId
			}).limit(10).skip(skip)
			.get()
			.then(res => res.data)
			.catch(err => err)
	}
}
// 获取单个模板
const getTempitem = async (_id) => {
	console.log('getTempitem', _id);
	return await db.collection('user-works').doc(_id)
		.get()
		.then(res => res.data)
		.catch(err => err)
}